package com.cheer.job;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.concurrent.*;


/**
 * @author cheer
 */
@Component
@Slf4j
public class ExPresentListener implements ApplicationListener<ApplicationReadyEvent> {

    protected static LinkedBlockingDeque<ExPresentTask> queue = new LinkedBlockingDeque<>();

    private ExecutorService executorService = Executors.newFixedThreadPool(50);

    private static Semaphore semaphore = new Semaphore(50);

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        new Thread(() -> {
            while (true) {
                try {
                    ExPresentTask task = queue.take();

                    semaphore.acquire();

                    executorService.submit(task);

                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
        }).start();
    }

    public static void putTask(Integer id, String serviceId) {
        ExPresentTask learnTask = new ExPresentTask(id, serviceId, semaphore);
        try {
            queue.put(learnTask);
        } catch (InterruptedException e) {
            log.error(e.getMessage(), e);
        }
    }
}